var fs = require('fs');
var path = require('path');
var wordRules = require(path.join(__dirname,'../wordRules/wordRules.js')).wordRules; //引入关键字数组和运算符
/*var url = path.normalize(__dirname + '/less')*/
/*开始词法分析*/
String.prototype.test = function(string) {
    var temp = string.match(this);
    if (temp != null) {
        return true;
    } else {
        return false;
    }
};
String.prototype.exactMatch = function(regex) { //为字符串添加绝对等长匹配
    if (regex.test(this)) {
        var matched = this.match(regex);
        if (matched[0].length === this.length) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
var hasMatched = function(string) {
    for (var i = 0; i < wordRules.length; i++) {
        if (string.exactMatch(wordRules[i])) {
            return true;
        }
    }
    return false;
}
exports.parseWords = function(url) {
    var codingString = fs.readFileSync(url).toString(); //通过FileSystem模块读取出less脚本的代码
    codingString = codingString.replace(/[\r\n]/g, ''); //去掉代码中所有的换行符号
    codingString += " "; //加上一个空格作为终结
    var wordsArray = new Array(); //创建单词数组
    var wordTemp = ""; //创建临时字符串
    var inString = false;//判断是否在解析字符串值
    for (var i = 0; i < codingString.length - 1; i++) {
        if (codingString[i] != ' ' && codingString[i] != "	" && !inString) {
            if (codingString[i] == "\"") {
                wordsArray.push("\"");
                inString = true;
                continue;
            }
            wordTemp += codingString[i];
            if (!hasMatched(wordTemp + codingString[i + 1])) {
                wordsArray.push(wordTemp);
                wordTemp = "";
            }
        }
        if (inString) {
            if (codingString[i] == "\"") {
                wordsArray.push(wordTemp);
                wordsArray.push("\"");
                inString = false;
                wordTemp = "";
                continue;
            }
            wordTemp += codingString[i];
        }
    }
    return wordsArray;
}